package com.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.dao.UserDao;
import com.dao.imp.UserDaoimpl;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/Export")
@MultipartConfig
public class Export extends HttpServlet {
    UserDao userDao  = new UserDaoimpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Object> list= null;
        try {

            list = userDao.selectAllCompanyList(req, resp);
            System.out.println("list = " + list);
            ExcelWriter writer = ExcelUtil.getWriter(true);
            //与实体类的变量名对应
            writer.addHeaderAlias("companyId","公司账号");
            writer.addHeaderAlias("companyName","公司名");
            writer.addHeaderAlias("companyAddress","公司地址");
            writer.addHeaderAlias("companyTel","公司电话");
            writer.addHeaderAlias("companyEmail","公司邮箱");
            writer.addHeaderAlias("addTime","注册时间");
            writer.addHeaderAlias("gongNum","工商号");
            writer.addHeaderAlias("state","状态");

            writer.write(list,true);

            //设置浏览器响应格式
            resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            String fileName = URLEncoder.encode("公司信息", "UTF-8");
            resp.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

            ServletOutputStream out = resp.getOutputStream();
            writer.flush(out,true);
            out.close();
            writer.close();
            resp.getWriter().write("success");

        } catch (SQLException e) {
            e.printStackTrace();
        }

        super.service(req, resp);
    }
}
